/*
 * $Id: SyncHttpConnection.java 224 2008-03-27 07:02:30Z jasta $
 *
 * Copyright (C) 2008 Josh Guilfoyle <jasta@devtcg.org>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 */

package org.devtcg.syncml.transport;

import java.net.URI;
import java.io.IOException;
import java.io.EOFException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

import org.devtcg.syncml.protocol.SyncPackage;

public class SyncHttpConnection extends SyncConnection
{
	protected HttpClient mClient;
	protected String mURI;
	
	private String mResponse;

	public SyncHttpConnection(String uri)
	{
		this(uri, uri);
	}

	public SyncHttpConnection(String uri, String name)
	{
		super(name);
		mURI = uri;
	}

	public void open()
	{
		mOpened = true;
		mClient = new HttpClient(new SimpleHttpConnectionManager());
	}

	public void close()
	{
		/* XXX */
		mOpened = false;
//		mClient.getHttpConnectionManager().shutdown();
		mClient = null;
	}

	public void sendPackage(String msg)
	  throws IOException
	{
//		HttpClient mClient = new HttpClient();

		PostMethod post = new PostMethod(mURI);

		RequestEntity entity = new StringRequestEntity(msg, "application/vnd.syncml+xml", "UTF-8");
		post.setRequestEntity(entity);

		try
		{
			int status = mClient.executeMethod(post);

			/* XXX: We mandate UTF-8 encoding here... */
			mResponse = new String(post.getResponseBody(), "UTF-8");
		}
		finally
		{
			post.releaseConnection();
		}
	}

	public String recvPackage()
	  throws IOException
	{
		if (mResponse == null)
			throw new EOFException("XXX");

		return mResponse;
	}
}
